package com.wgu.modules.service.impl;

import com.wgu.entity.AuthorInfo;
import com.wgu.modules.dto.AddAuthorDTO;
import com.wgu.modules.mapper.AddAuthorMapper;
import com.wgu.modules.repository.AuthorRepository;
import com.wgu.modules.service.AuthorService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author: w
 * @Date: 2019/7/4 9:22
 * @Version 1.0
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AuthorServiceImpl implements AuthorService {
    @Resource
    private AuthorRepository authorRepository;
    @Resource
    private AddAuthorMapper addAuthorMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAuthor(AddAuthorDTO addAuthorDTO) {
        authorRepository.save(addAuthorMapper.toEntity(addAuthorDTO));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AuthorInfo getAuthor(String name) {
        AuthorInfo authorInfo = authorRepository.findByAuthName(name).orElse(new AuthorInfo());
        if(authorInfo.getId()==null){
            authorInfo.setAuthName(name);
            authorInfo = authorRepository.save(authorInfo);
        }
        return authorInfo;
    }
}
